package com.awenhui.demo.core.utils;

import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.awenhui.demo.config.Person;
import com.awenhui.demo.core.utils.icbc.IcbcSign;
import com.awenhui.demo.core.utils.poi.CellActionArgs;
import com.awenhui.demo.core.utils.poi.ExcelStyle;
import com.awenhui.demo.core.utils.poi.WordUtils;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.SerializationUtils;
import org.springframework.util.StopWatch;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * java基础
 *
 * @author yuxf
 * @version 1.0
 * @date 2020/5/12 9:03
 */
public class JavaBasic extends Thread {

    public static void main(String[] args) throws Exception {
        String ipconfig = RuntimeUtil.execForStr("echo 'test'");
        System.out.println(ipconfig);
    }


    /**
     * 生成编号
     * - 验证码[rand:4]或[guid:4]
     * - 优惠券码或邀请码：[rand:9]
     * - 有序编号 TD[date:yyyyMMdd][sno:4]
     * - 文件路径 /uploads/images/[date:yyyyMMdd]/[guid:18].jpg
     * -
     *
     * @param pattern 模式，如/images/[date:yyyyMMdd]/[guid]-[rand:3]-[sno:3].jpg
     *                - [rand:3] 三位随机数
     *                - [guid:8] 8位随机字符串，最长32位
     *                - [date:yyyyMMdd] 日期格式化
     *                - [sno:3] 3位有序编号，需要传入上次编号，内部会自动加1
     * @param sno     当前流水号，如果不是生成流水号则传0
     * @return
     */
    public static String getNo(String pattern, int sno) {
        //  String input = "/images/[sno:3]/[rand]/[date:yyyyMMdd]-[rand:3]-[guid].jpg";
        Matcher matcher = Pattern.compile("\\[([A-Za-z0-9]+)(\\:?)([A-Za-z0-9]*)\\]").matcher(pattern);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String type = matcher.group(1);
            String patternItemStr = "";
            //如果没有指定长度，默认为8
            String lengthStr = matcher.group(3);

            int length = 8;
            if (!"".equals(matcher.group(3)) && !type.equals("date")) {
                length = Integer.parseInt(matcher.group(3));
            }
            switch (type) {
                case "rand":
                    patternItemStr = new Random().ints(0, 10).limit(length).boxed().map(s -> s + "").collect(Collectors.joining());
                    break;
                case "sno":
                    patternItemStr = String.format("%0" + length + "d", sno + 1);
                    break;
                case "date":
                    SimpleDateFormat sdf = new SimpleDateFormat(lengthStr);
                    patternItemStr = sdf.format(new Date());
                    break;
                case "guid":
                    patternItemStr = UUID.randomUUID().toString().replace("-", "").substring(0, length);
                    break;
                default:
                    break;
            }
            matcher.appendReplacement(sb, patternItemStr);
        }
        String result = matcher.appendTail(sb).toString();
        return result;
    }


    //验证码
    public static void captcha() throws IOException {
        DefaultManageableImageCaptchaService captchaService = new DefaultManageableImageCaptchaService();
        captchaService.setCaptchaEngine(new CaptchaEngine());
        BufferedImage imageChallengeForID = captchaService.getImageChallengeForID("1");
        ImageIO.write(imageChallengeForID, "jpg", new File("d:\\demo\\captcha" + System.currentTimeMillis() + ".jpg"));
        captchaService.validateResponseForID("1", "123".toUpperCase());
        System.out.println("验证码生成成功");
    }


    public static void randomNo() throws InterruptedException {
        double random = Math.random() * 1000000;

        System.out.println(String.format("%06d", (int) random));
    }

    /**
     * 发送短信
     */
    public static void sendSms(String mobile) throws ClientException {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //替换成你的AK
        final String accessKeyId = "LTAI4GDYibJxd9NnVXiLAeyk";//你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "vppmW5Js6e4IIIfeLb3d81XuRzUgCS";//你的accessKeySecret，参考本文档步骤2
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("赛岭公寓");
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode("SMS_199195139");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        //参考：request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")
        request.setTemplateParam("{\"name\":\"于新方\"}");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
        //请求成功
            System.out.println("发送成功");
        } else {
            System.out.println(sendSmsResponse.getCode());
        }
    }


    public static void serialize() throws IOException, ClassNotFoundException {
        List<PersonJb> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(new PersonJb("于方方" + i, i + 15));
        }
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\demo\\ser.txt"));
        oos.writeObject(list);
        oos.close();
        System.out.println("序列化成功");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\demo\\ser.txt"));
        List<PersonJb> personJbs = (List<PersonJb>) ois.readObject();
        System.out.println("反序列化结果：" + Arrays.toString(personJbs.toArray()));
        ois.close();
    }

    /**
     * 测试支付回调
     */
//    public static void testCallback()  {
//        ////回调数据
////        {
////            "charset":"UTF-8",
////                "biz_content":"{\"attach\":\"mer_var:data\",\"bank_disc_amt\":\"0\",\"card_flag\":\"\",\"card_no\":\"\",\"coupon_amt\":\"0\",\"cust_id\":\"\",\"decr_flag\":\"\",\"ecoupon_amt\":\"0\",\"mer_disc_amt\":\"0\",\"mer_id\":\"240207011184\",\"msg_id\":\"050202150210818161440141709\",\"open_id\":\"ow8NuxGOSI43OB_rAqIgsgEhD4vI\",\"order_id\":\"240207011184000712007280005001\",\"out_trade_no\":\"TS1595923932383\",\"pay_time\":\"20200728161440\",\"pay_type\":\"9\",\"payment_amt\":\"1\",\"point_amt\":\"0\",\"return_code\":\"0\",\"return_msg\":\"交易成功\",\"third_trade_no\":\"4200000572202007282592711329\",\"total_amt\":\"1\",\"total_disc_amt\":\"0\"}",
////                "format":"json",
////                "sign":"id+UgfaNolisTdsalRkPv0TIKW2SJuMW+oz+D+e5lzZXydhSmSJDz40dLRp9ifIFDB10Vo1Ck+Dc+obiYMJE8wmSpp4GSSqAm/hqMEhjCW47iJw+SoUElnMtUMETLVAUJrI5NyV/3wweRMYWiC3redhiMylJHptTkbZSaTq0tlo=",
////                "from":"icbc-api",
////                "api":"/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1",
////                "app_id":"10000000000003160185",
////                "sign_type":"RSA",
////                "timestamp":"2020-07-28 16:14:41"
////        }
//        ////biz_content
////        {
////            "attach":"mer_var:data",
////                "bank_disc_amt":"0",
////                "card_flag":"",
////                "card_no":"",
////                "coupon_amt":"0",
////                "cust_id":"",
////                "decr_flag":"",
////                "ecoupon_amt":"0",
////                "mer_disc_amt":"0",
////                "mer_id":"240207011184",
////                "msg_id":"050202150210818161440141709",
////                "open_id":"ow8NuxGOSI43OB_rAqIgsgEhD4vI",
////                "order_id":"240207011184000712007280005001",
////                "out_trade_no":"TS1595923932383",
////                "pay_time":"20200728161440",
////                "pay_type":"9",
////                "payment_amt":"1",
////                "point_amt":"0",
////                "return_code":"0",
////                "return_msg":"交易成功",
////                "third_trade_no":"4200000572202007282592711329",
////                "total_amt":"1",
////                "total_disc_amt":"0"
////        }
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("from", "icbc-api");
//        params.put("api", "/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1");
//        params.put("app_id", "10000000000003160185");
//        params.put("charset", "UTF-8");
//        params.put("format", "json");
//        params.put("encrypt_type", "");
//        params.put("timestamp", "2020-07-28 16:14:41");
//        params.put("biz_content", "{\"attach\":\"mer_var:data\",\"bank_disc_amt\":\"0\",\"card_flag\":\"\",\"card_no\":\"\",\"coupon_amt\":\"0\",\"cust_id\":\"\",\"decr_flag\":\"\",\"ecoupon_amt\":\"0\",\"mer_disc_amt\":\"0\",\"mer_id\":\"240207011184\",\"msg_id\":\"050202150210818161440141709\",\"open_id\":\"ow8NuxGOSI43OB_rAqIgsgEhD4vI\",\"order_id\":\"240207011184000712007280005001\",\"out_trade_no\":\"TS1595923932383\",\"pay_time\":\"20200728161440\",\"pay_type\":\"9\",\"payment_amt\":\"1\",\"point_amt\":\"0\",\"return_code\":\"0\",\"return_msg\":\"交易成功\",\"third_trade_no\":\"4200000572202007282592711329\",\"total_amt\":\"1\",\"total_disc_amt\":\"0\"}");
//        params.put("sign_type", "RSA");//目前上行网关签名暂时仅支持RSA
//        //notify_url=http://122.20.29.133:9081/notifyUrlServlet
//        //http://139.159.190.0:8080/sail-web/icbcPay/callbackTest
//        String path = "/sail-web/icbcPay/callbackTest";
//        String signStr = IcbcSign.buildOrderedSignStr(path, params);
//        String results = null;
//        String responseBizContent = null;
//        try {
//            System.out.println("公钥：" + IcbcSign.GATEWAY_PUBLIC_KEY);
//            String sign = "id+UgfaNolisTdsalRkPv0TIKW2SJuMW+oz+D+e5lzZXydhSmSJDz40dLRp9ifIFDB10Vo1Ck+Dc+obiYMJE8wmSpp4GSSqAm/hqMEhjCW47iJw+SoUElnMtUMETLVAUJrI5NyV/3wweRMYWiC3redhiMylJHptTkbZSaTq0tlo=";
//            boolean flag = IcbcSignature.verify(signStr, "RSA", IcbcSign.GATEWAY_PUBLIC_KEY, "UTF-8", sign);
//            System.out.println("工行验证结果：" + flag);
//            boolean verify = IcbcSign.verify(signStr, sign);
//            System.out.println("本地方法验证：" + verify);
//        } catch (Exception ex) {
//            System.out.println(ex.getMessage());
//        }
//
//    }

    private static void testLog() throws IOException {
        LogUtils.writeLog("测试测试", "/home/log/");
        LogUtils.writeLog("测试测试", "d:\\demo\\test\\log.txt");
        LogUtils.writeLog(System.currentTimeMillis() + "测试测试--", "d:\\demo\\test");
        System.out.println("成功");
    }

    private static void testSign() throws Exception {
        String dataStr = "/ui/cardbusiness/epaypc/consumption/V1?app_id=10000000000003160185&biz_content={\"amount\":\"0\",\"credit_type\":\"2\",\"cur_type\":\"001\",\"e_fixedACFlag\":\"0\",\"e_isMerFlag\":\"0\",\"elife_mer_id\":\"24020092169\",\"expire_time\":\"20200727124552\",\"goods_id\":\"G001\",\"goods_name\":\"RENT\",\"icbc_appid\":\"10000000000003160185\",\"icbc_flag\":\"1\",\"installment_times\":\"1\",\"language\":\"zh_CN\",\"mer_acct\":\"2402003429000043055\",\"mer_custom_ip\":\"117.187.226.178\",\"mer_hint\":\"TEST\",\"mer_id\":\"240207011184\",\"mer_prtcl_no\":\"2402070111840201\",\"mer_url\":\"https://blog.csdn.net/zsl471260400/article/details/80236569\",\"mer_var\":\"mer_var:data\",\"merchant_info\":\"TEST\",\"notify_type\":\"HS\",\"order_date\":\"20200727114552\",\"out_trade_no\":\"TS1595821552565\",\"page_linkage_flag\":\"1\",\"pay_expire\":\"600\",\"result_type\":\"0\",\"return_url\":\"https://www.baidu.com/\",\"verify_join_flag\":\"0\"}&charset=UTF-8&format=json&msg_id=6ebf93d7f3554cb8b4e9279541d2e7ca&sign_type=RSA2&timestamp=2020-07-27 11:46:37";
        String icbcSign = "SbhbfwGy5MLk9QWWe8K4q8YbXE240JAeqS0DfKn8g+Q52TH3a42fgCGU+b8S0FZKTtRcH17qALeLx+GLDfh6vhcDs8w56Q1ZuRX7kJ7opXpFCvHr/4XRoUkJ7QF+cSjoUiKIJp6on6mGq3g4IwZ0Ro+zPr9apyvFvES2akLBL+LstyDaPjxP/t+/AVD68YNUGo0Jg4wgxowIVCoIhEwl9vh0DC7v8cJ1c0WQc5JWMDfZH6R0i+itcy/VVXoY8VW0LLhE9QAMxogu1Zv8Wzy/B1lQ3G/9LUj3MusAVDjHoIPSMIjwvciJLUr/ZmHobqcNCZ9/9OTUtm/mcotlkOWC8A==";
        String sign = IcbcSign.sign(dataStr);
        System.out.println("工行签名" +
                "：" + icbcSign);
        System.out.println("自己签名：" + sign);
        System.out.println("验签结果：" + sign.equals(icbcSign));
    }

    private static void generic() {


    }

    static void fileTest() {
        File file = new File("d\\demo\\cat.mp4");
        File path = new File("d:\\demo\\test");
        System.out.println("file.getName:" + file.getName());
        System.out.println("path.getName:" + path.getName());
        System.out.println("file.getParent:" + file.getParent());
        System.out.println("path.getParent:" + path.getParent());
    }

    static void testTreeSet() throws IOException {

    }

    public static String compareStr(String str1, String str2) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str1.length(); i++) {

            char c1 = str1.charAt(i);
            char c2 = str2.charAt(i);
            if (c1 != c2 && i < 500) {
                sb.append(i + ":" + c1 + ">>" + c2 + "--");
                System.out.println(str1.substring(i - 20, i + 10) + ">>" + str2.substring(i - 20, i + 10));
            }

        }
        return sb.toString();

    }

    /**
     * 根据模板生成word并转换为pdf
     *
     * @throws Exception
     */
    static void createWord() throws Exception {
        //生成word
        String targetDoc = "d:\\demo\\" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss")) + ".doc";
        HashMap<String, String> params = new HashMap<>();
        params.put("$applicantName$", "于方方");
        params.put("$applicantCardCode$", "520101199002010025");
        params.put("$contractCode$", System.currentTimeMillis() + "");

        WordUtils.createWord("d:\\demo\\contract.doc", targetDoc, params);
        System.out.println(targetDoc + "生成成功");
        String pdf = targetDoc.replace(".doc", ".pdf");
        // WordUtils.getLicense();
        // WordUtils.wordToPdf(targetDoc, pdf);
        System.out.println(pdf + "生成成功");
    }

    static Consumer<CellActionArgs> action = new Consumer<CellActionArgs>() {
        @Override
        public void accept(CellActionArgs cellActionArgs) {
            ExcelStyle style = new ExcelStyle(cellActionArgs.getWorkbook());
            // cellActionArgs.getCell().setCellStyle(style.setAlignmentCenter().setDangerColor().build());
            cellActionArgs.getRow().setHeight((short) (22 * 20));
        }
    };
}







